﻿$.fn.extend({
    uploadImagePreview: function (opts) {
        var options = {
            previewContainerID: null,
            beforeLoad: null,
            loadedImage: null,
            imgWidth: 45
        };

        $.extend(options, opts);

        if (!options.previewContainerID) return this;

        var inputfileID = this.attr("id"), previewImg = null;

        this.reset = function () {
            $(previewImg).remove();
            previewImg = null;
        }

        this.bind("change", function () {
            if (typeof (options.beforeLoad) == "function") {
                options.beforeLoad.call();
            }

            if (FileReader) {
                var reader = new FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
                var hasFile = this.files && this.files[0];

                if (!hasFile) return;

                reader.onload = function (e) {
                    if (!previewImg) {
                        var newPreview = $("#" + options.previewContainerID);

                        previewImg = new Image();
                        previewImg.style.height = newPreview.height() + "px";
                        newPreview.empty().append(previewImg);
                    }

                    previewImg.src = e.target.result;

                    var img = $(previewImg);
                    var marginLeft = parseInt((options.imgWidth - img.width()) / 2);
                    marginLeft += marginLeft % 2;

                    if (marginLeft < 0) img.css("margin-left", marginLeft);

                    if (typeof (options.loadedImage) == "function") {
                        options.loadedImage.call();
                    }
                };

                var file = this.files[0];
                if (!rFilter.test(file.type)) { return; }
                reader.readAsDataURL(file);

                return;
            }
            if (navigator.userAgent.indexOf('MSIE') > -1) {
                document.getElementById(options.previewContainerID).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = document.getElementById(inputfileID).value;

                if (typeof (options.loadedImage) == "function") {
                    options.loadedImage.call();
                }
            }
        });

        return this;
    }
});